import React, { useState, useRef, useEffect } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect, history } from 'umi'
import { message, Button, Modal, Form, Input, Row, Col, Divider, Table } from 'antd'
import { getMenuEntityList, updateMenuInterface, deleteMenu, addMenuInterface } from '../service'

const setTree = (treeList, list) => {
  treeList.forEach(item => {
    item['key'] = item.menuId;
    item['children'] = [];
    for (let i=0; i<list.length; i++){
      if (list[i].parentId === parseInt(item.menuId)){
        item['children'].push(list[i]);
      }
    }
    setTree(item['children'], list)
  });
  return treeList;
};

const TableList = (props) => {
  const [menuTree, setMenuTree] = useState([]);
  const [title, setTitle] = useState('');
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(null);
  const [loading, setLoading] = useState(false);
  const [selectionType, setSelectionType] = useState('radio');
  const [selectedMenuIds, setSelectedMenuIds] = useState([]);
  const [menuInfo, setMenuInfo] = useState({});

  const init = () => {
    getMenuEntityList('').then(res => {
      let menuParents = res.filter(item => { return item.parentId === 0});
      let menuTree = setTree(menuParents, res);
      setMenuTree(menuTree);
    });
  };

  useEffect(() => {
    init();
  }, []);

  const addMenu = (value) => {
    setTitle('添加菜单');
    setVisible(true);
    setMenuInfo(value);
  };

  const updateMenu = (value) => {
    setTitle('编辑菜单');
    setVisible(true);
    setMenuInfo(value);
    form.setFieldsValue(value);
  };

  const delMenu = (value) => {
    setLoading(true);
    deleteMenu(parseInt(value.menuId)).then(r => {
      if (r.flag){
        message.success(`删除菜单成功。`);
      }else {
        message.error(`删除菜单失败。`);
      }
      init();
      setLoading(false);
    })
  };

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedMenuIds(selectedRowKeys);
    }
  };

  const handleCancel = () => {
    setVisible(false);
    form.resetFields();
  };

  const handleSubmit = (values) => {
    setLoading(true);
    setVisible(false);
    if (title === '添加菜单'){
      let data = {
        parentId: menuInfo.menuId,
        type: 1,
        ...values
      };
      addMenuInterface(data).then(r => {
        if (r.flag){
          message.success(`新增菜单成功。`);
        }else {
          message.error(`新增菜单失败。`);
        }
        init();
        setLoading(false);
      });
    }else if (title === '编辑菜单'){
      let {children, ...data} = menuInfo;
      data.name = values.name;
      data.url = values.url;
      updateMenuInterface(data).then(r => {
        if (r.flag){
          message.success(`编辑菜单成功。`);
        }else {
          message.error(`编辑菜单失败。`);
        }
        init();
        setLoading(false);
      })
    }
    form.resetFields();
  };

  const columns = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      width: '20%'
    },
    {
      title: 'url配置',
      dataIndex: 'url',
      width: '55%'
    },
    {
      title: '操作',
      dataIndex: 'option',
      render: (item, record) => (
        <>
          {<a onClick={() => addMenu(record)}>添加子菜单</a>}
          {<Divider type="vertical" />}
          {<a onClick={() => updateMenu(record)}>编辑</a>}
          {}
          {record.parentId !== 0 ? <><Divider type="vertical" /><a onClick={() => delMenu(record)}>删除</a></> : ''}
        </>
      ),
    },
  ];


  return (
    <PageHeaderWrapper>
      <Table
        columns={columns}
        loading={loading}
        // rowSelection={{ ...rowSelection, type:'radio' }}
        dataSource={menuTree}
      />

      <Modal
        maskClosable={false}
        title={title}
        visible={visible}
        footer={null}
        closable={false}
      >
        <Form
          form={form}
          // initialValues={}
          onFinish={handleSubmit}
        >
          <Form.Item name="name">
            <Input placeholder="菜单名称" />
          </Form.Item>
          <Form.Item name="url">
            <Input placeholder="菜单url配置" />
          </Form.Item>
          <Row justify='end' gutter={16}>
            <Col className="gutter-row" style={{paddingBottom: '20px'}}>
              <Button onClick={handleCancel} style={{marginRight: '12px'}} >取消</Button>
              <Button type="primary" htmlType="submit">保存</Button>
            </Col>
          </Row>
        </Form>
      </Modal>

    </PageHeaderWrapper>
  )
};

export default connect(({global}) => ({
  global
}))(TableList)
